import store from "@/store";
import Cache from '@/utils/cache';
import { Debounce } from '@/utils/base'
import { LOGIN_STATUS, USER_INFO, EXPIRES_TIME, STATE_R_KEY, BACK_URL, GLOBAL_DATA} from '@/config/store.js';
// #ifdef H5 || APP-PLUS
import { isWeixin } from "../utils";
import auth from './wechat';
// #endif
function prePage(){
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 1];
	// #ifndef APP-PLUS
	return prePage.route;
	// #endif
	// #ifdef APP-PLUS
	return prePage.$page.fullPath;
	// #endif
}

export const toLogin = Debounce(_toLogin,800)
// export const toUserLogin = Debounce(_toLogin(),800)

export function _toLogin(push, pathLogin) {
	// 公众号登录方式(单选),1微信授权，2手机号登录/
	// let publicLoginType = getApp().globalData.publicLoginType;
	let url = '/pages/group/login/index';
	console.log('url',url)
	store.commit("LOGOUT");
	// store.commit("LOGOUT_USER");
	let path = prePage();
	let login_back_url = Cache.get(BACK_URL);
	// #ifdef H5
	path = location.href;
	path = location.pathname + location.search;
	// #endif
	if(!pathLogin){
		pathLogin = url
		Cache.set(BACK_URL,path);
	}
	// #ifdef H5
	console.log('isWeixin()',isWeixin())
	if (isWeixin()) {
		let urlData = location.pathname + location.search
		if (urlData.indexOf('?') !== -1) {
			urlData += '&go_longin=1';
		} else {
			urlData += '?go_longin=1';
		}
		console.log('snsapiKey',Cache.has('snsapiKey'))
		if (!Cache.has('snsapiKey')) {
			// console.log('urlData',urlData)
			uni.navigateTo({
				url: url + location.search
			})
			// auth.oAuth('snsapi_base', urlData);
		} else {
			uni.navigateTo({
				url: url + location.search
			})
		}
	} else {
		uni.navigateTo({
			url: url + location.search
		})
	}
	// #endif
}

export function checkLogin()
{
	// console.log('44444')
	let token = Cache.get( );
	let expiresTime = Cache.get(EXPIRES_TIME);
	let newTime = Math.round(new Date() / 1000);
	if (expiresTime < newTime || !token){
		Cache.clear(LOGIN_STATUS);
		Cache.clear(EXPIRES_TIME);
		Cache.clear(USER_INFO);
		Cache.clear(STATE_R_KEY);
		return false;
	}else{
		store.commit('UPDATE_LOGIN',token);
		let userInfo = Cache.get(USER_INFO,true);
		if(userInfo){
			store.commit('UPDATE_USERINFO',userInfo);
		}
		return true;
	}

} 